﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;
using Cmd;
using Radio;

//电台数据
public class RadioDataPool
{
    public static int ConnectServerTimes = 0;
    public const string defaultUrl = "http://www.soulgame.mobi";
    public const string dataPath = "Radio/radio_data/RadioTagDataConfig.asset";
    public const string UIPath = "radio/radio_ui/DiantaiUIForm";

    public static Rect imgRect = new Rect(0f,0f,1269f,586f);
    public static Rect imgTabRect = new Rect(0f, 0f, 246f, 187f);
    public static string screenShotFile
    {
        get
        {
            return Application.persistentDataPath + "/screen.png";
        }
    }

    /// <summary>
    /// 存储在playerefs中的数据[格式-  id,md5|id,md5|id,md5]
    /// </summary>
    public const string storeDataID = "RadioDownloadFiles";

    public static string fileSavePath
    {
        get
        {
            string sdCardPath = SDKManager.Instance.GetSdcardPath();
            if (string.IsNullOrEmpty(sdCardPath))
            {
                sdCardPath = Application.persistentDataPath;
            }
            sdCardPath = FileTools.CombinePath(sdCardPath, "SuperwingsImage");
            if (!FileTools.IsDirectoryExist(sdCardPath))
                FileTools.CreateDirectory(sdCardPath);
            return sdCardPath + "/";
        }
    }

    private static RadioDataPool m_Instance;
    public static RadioDataPool Instance
    {
        get
        {
            if (m_Instance == null)
                Init();
            return m_Instance;
        }
    }

    public RadioTagDataConfig localConfig;          //本地配置
    public bool pushFM = true;                      //SDK是否推送
    public ReturnRadioInfo serverData;              //服务器端数据
    public bool isServerDataReady = false;          //服务器端数据是否OK

    public List<RadioDownLoadItem> downloadList;    //下载列表
    public List<RadioTagViewItem> tabViewList;      //大分类
    public List<RadioViewItem> radioItemList;       //小分类

    public Dictionary<string, Texture2D> textures = new Dictionary<string, Texture2D>();
    static void Init()
    {
        m_Instance = new RadioDataPool();
        m_Instance.LocalConfigLoad();
    }

    RadioDataPool()
    {

    }

    public void TryGetServerData()
    {
        new RadioHttp().ConnectServer(SuccessCallback, FailCallback);
    }

    void SuccessCallback(byte[] bytes)
    {
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.Radio_Net_Loading,new stUIEventParams { argInt=1});

        ReturnRadioInfo radioinfo = Protocol.ProtoBufDeserialize<ReturnRadioInfo>(bytes);
        RadioDataPool.Instance.ServerDataInsert(radioinfo);
        DiantaiMainCtr.Instance.ReportModuleState(RadioModuleEnum.ConnectServer);
        Debug.Log(radioinfo.status);
        if (radioinfo.album != null)
        {
            for (int i = 0; i < radioinfo.album.Count; i++)
            {
                Album item = radioinfo.album[i];
                string str1 = string.Format("id:{0} buy:{1} 描述:{2} 名字:{3} 排序:{4} 价格:{5} 状态:{6} 封面:{7} |\n", new object[] {
                    item.cid,
                    item.buy,
                    item.desc,
                    item.name,
                    item.order,
                    item.price,
                    item.status,
                    item.cover_url,
                });
                List<RadioInfo> list = item.radioList;
                for (int j = 0; j < list.Count; j++)
                {
                    RadioInfo riItem = list[j];
                    string str = string.Format("id:{0} 排序:{1} 名字:{2} 状态:{3} 免费:{4} 地址:{5} 封面:{6} 描述:{7} 推荐:{8}\n", new object[]
                    {
                        riItem.rid,
                        riItem.order,
                        riItem.name,
                        riItem.status,
                        riItem.free,
                        riItem.addr,
                        riItem.cover_url,
                        riItem.desc,
                        riItem.is_recommand
                    });
                    str1 += str;
                }
                //Debug.Log(str1);
                //Debug.Log(item.good_id + "   " + item.buy);
            }
            AssembleData();
        }
    }

    void FailCallback(emHttpRequestState state)
    {
        throw new System.Exception(state.ToString());
    }


    //本地数据load
    public void LocalConfigLoad()
    {
        Resource resource;
        resource = ResourceManager.Instance.GetResource(dataPath, null, enResourceType.Prefab);
        //Debug.Log(resource.m_content.ToString());
        m_Instance.localConfig = resource.m_content as RadioTagDataConfig;
    }

    //链接SDK:决定推还是不推彩虹儿童FM
    public void ConnectSDK()
    {
        pushFM = SDKManager.Instance.isRainbowFM();
        Debug.Log(pushFM);
    }
    


    //服务器数据insert
    public void ServerDataInsert(ReturnRadioInfo returnRadioInfo)
    {
        serverData = returnRadioInfo;
        isServerDataReady = true;
    }

    //服务器数据更新(购买引起的变化)
    public void ServerDataUpdate()
    {
        pushFM = true;
    }

    //释放：释放掉服务器端的数据
    public void Release()
    {
        serverData = null;
        downloadList = null;
        tabViewList = null;
        radioItemList = null;
        textures.Clear();
    }

    //组装数据
    public void AssembleData()
    {
        //0.数据写入playerefs
        //1.拼装下载数据 List
        //2.拼装展示数据
        if (serverData == null) return;

        List<RadioDownLoadItem> storeList = new List<RadioDownLoadItem>();//记录本次所有信息

        string storeStr = PlayerPrefs.GetString(storeDataID,"");
        Debug.Log(storeStr);
        List<RadioDownLoadItem> lastVersionList = new List<RadioDownLoadItem>();
        if (storeStr != "")
            lastVersionList = storeStr.Deserialize();//前一次信息
        if (serverData.album != null)
        {
            //download list
            downloadList = new List<RadioDownLoadItem>();
            //

            for (int i = 0; i < serverData.album.Count; i++)
            {
                Album item = serverData.album[i];

                //过滤掉未上架商品
                if (item.status == 0)
                    continue;
                if (item.buy == 1)
                {
                    for (int k = 0; k < item.radioList.Count; k++)
                        item.radioList[k].free = 1;
                }

                //download
                RadioDownLoadItem downloadItem0 = new RadioDownLoadItem();
                downloadItem0.itemId = item.cid.ToString();
                downloadItem0.coverUrl = item.cover_url;
                if (SatisfyDownloadCondition(lastVersionList,downloadItem0))
                    downloadList.Add(downloadItem0);

                storeList.Add(downloadItem0);

                for (int j = 0; j < item.radioList.Count; j++)
                {
                    RadioInfo radioInfo = item.radioList[j];

                    //过滤掉未上架商品
                    if (radioInfo.status == 0)
                        continue;

                    //download
                    RadioDownLoadItem downloadItem1 = new RadioDownLoadItem();
                    downloadItem1.itemId = item.cid.ToString() + "_" + radioInfo.rid.ToString();
                    downloadItem1.coverUrl = radioInfo.cover_url;
                    if(SatisfyDownloadCondition(lastVersionList, downloadItem1))
                    downloadList.Add(downloadItem1);

                    storeList.Add(downloadItem1);
                }
            }

            string saveStr = "";
            for (int i = 0; i < storeList.Count; i++)
            {
                saveStr += storeList[i].GetDownloadKeyString();
                if (i != storeList.Count - 1)
                    saveStr += "|";
            }
            if(saveStr!="")
            PlayerPrefs.SetString(storeDataID,saveStr);

            Debug.Log("下载列表数量:" + downloadList.Count);
            if (ConnectServerTimes == 0)
            {
                StartDownloadModule();
                Release();
            }
            else
            {
                DiantaiMainCtr.Instance.ReportModuleState(RadioModuleEnum.AssembleData);
                InitRadioPlayer();
            }
            ConnectServerTimes++;
        }

        
    }

    protected void InitRadioPlayer()
    {
        string json =
        GetJsonByTabID(-1);

        string j = json;
        j = j.Replace("{\"Data\":[", "[");
        j = j.Replace("]}", "]");

        //Debug.Log(j);
#if UNITY_EDITOR
        RadioSDKManager.Instance.InitRadio(json);
        Debug.Log(json);
#else

        RadioSDKManager.Instance.InitRadio(j);
        
#endif
    }

    protected bool SatisfyDownloadCondition(List<RadioDownLoadItem> list, RadioDownLoadItem tmp)
    {
        //Debug.Log(tmp.itemId + " ::: " + tmp.localCoverFileUrl);
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].itemId == tmp.itemId)
            {

                if (list[i].coverUrl == tmp.coverUrl)
                {
                    return !FileTools.IsFileExist(tmp.localCoverFileUrl);
                }
                else
                    return false;
                //下载路径一样，本地也存在文件，文件完整。不加入下载列表
            }
        }
        return true;
    }

    protected GameObject downloadMoudle;
    protected void StartDownloadModule()
    {
        if (downloadList == null || downloadList.Count == 0) return;
        downloadMoudle = new GameObject("Radio_Download");
        downloadMoudle.AddComponent<RadioResDownload>().Set(downloadList, null, null, null);
    }
    
    //获取某一个分类的展示数据
    public List<RadioViewItem> GetViewData(int cid)
    {
        List<RadioViewItem> list = new List<RadioViewItem>();
        if (localConfig.needServer)
        {
            if (serverData != null &&serverData.album!=null)
            {
                if (cid == -1)
                {
                    list = GenerateRecommandData();
                }
                else
                {
                    for (int i = 0; i < serverData.album.Count; i++)
                    {
                        Album item = serverData.album[i];
                        if (item.cid == cid)
                        {
                            for (int j = 0; j < item.radioList.Count; j++)
                            {
                                RadioInfo ritem = item.radioList[j];
                                if (ritem.status == 0) continue;
                                RadioViewItem tmp = new RadioViewItem();
                                tmp.desStr = ritem.desc;
                                tmp.diversityNum = 0;
                                tmp.diversityTag = ritem.rid;
                                tmp.episodeTag = ritem.rid;
                                tmp.imgUrl = ritem.cover_url;
                                tmp.audioUrl = ritem.addr;
                                tmp.isDiversity = false;
                                tmp.itemState = ritem.free;
                                tmp.leadershipTag = item.cid;
                                tmp.nameStr = ritem.name;
                                list.Add(tmp);

                            }
                        }
                    }
                }
            }
        }
        else
        {
            int sum = Random.Range(6, 50);
            int i = 0;
            while (i++ < sum)
            {
                RadioViewItem tmp = new RadioViewItem();
                tmp.audioUrl = "";
                tmp.desStr = "qwert" + i;
                tmp.diversityNum = 0;
                tmp.diversityTag = 0;
                tmp.episodeTag = i;
                tmp.imgUrl = "";
                tmp.isDiversity = false;
                tmp.itemState = (i % 3);
                tmp.leadershipTag = i % sum0;
                if (cid == tmp.leadershipTag)
                    list.Add(tmp);
            }
        }
        //list.Sort();
        CollectionSort<RadioViewItem>.Sort(list, "leadershipTag ASC, episodeTag ASC");
        //for (int i = 0; i < list.Count; i++)
        //    Debug.Log(list[i].ToString());
        return list;
    }

    int sum0;
    //获取全部需要展示的数据
    public List<RadioTagViewItem> GetTabData()
    {
        if (tabViewList == null) tabViewList = new List<RadioTagViewItem>();
        else
            tabViewList.Clear();
        //推送
        if (pushFM && !GiftBagResManager.Instance.IsRainbowAppDownlaod)
        {
            RadioTagViewItem rainballFM = GetDefaultTab(RadioTagViewState.rainBallFM).Clone();
            tabViewList.Add(rainballFM);
        }
        RadioTagViewItem recommand = GetDefaultTab(RadioTagViewState.recommend).Clone();
        tabViewList.Add(recommand);
        RadioTagViewItem normal = GetDefaultTab(RadioTagViewState.normal);

        if (!localConfig.needServer)
        {
            //模拟数据
            sum0 = Random.Range(2, 5);
            for (int i = 0; i < sum0; i++)
            {
                RadioTagViewItem tmp = normal.Clone();
                tmp.tag = i + 1;
                tmp.tagDesStr = "超级飞侠" + tmp.tag;
                tmp.order = tmp.tag;
                tabViewList.Add(tmp);
            }
        }
        else
        {
            for (int i = 0; i < serverData.album.Count; i++)
            {
                Album item = serverData.album[i];
                //未上架，过滤
                if (item.status == 0) continue;
                RadioTagViewItem tmp = normal.Clone();
                tmp.tag = item.cid;
                tmp.imgUrl = item.cover_url;
                //Debug.Log(tmp.imgUrl);
                tmp.diversityNums = item.radioList.Count;
                tmp.nameStr = item.name;
                tmp.tagDesStr = item.desc;
                tabViewList.Add(tmp);
            }
        }
        tabViewList.Sort();
        //for (int i = 0; i < tabViewList.Count; i++)
        //    Debug.Log(tabViewList[i].tag);
        return tabViewList;
    }

    public void Jump2DownloadURL()
    {
        Application.OpenURL(defaultUrl);
    }

    public Album GetTabDataById(int cid)
    {
        for (int i = 0; i < serverData.album.Count; i++)
        {
            Album album = serverData.album[i];
            if (album.cid == cid)
                return album;
        }
        return null;
    }

    public void BuyAlbumSuccess(int goods_id)
    {
        if (serverData == null) return;
        for (int i = 0; i < serverData.album.Count; i++)
        {
            //if (serverData.album[i].cid == goods_id)
            if (serverData.album[i].good_id == goods_id)
            {
                Album album = serverData.album[i];
                album.buy = 1;
                for (int j=0;j<album.radioList.Count;j++)
                {
                    album.radioList[j].free = 1;
                }
                return;
            }
        }
    }

    //推荐搜集
    protected List<RadioViewItem> GenerateRecommandData()
    {
        List<RadioViewItem> list = new List<RadioViewItem>();
        if (serverData == null) throw new System.Exception("ServerData Null(Radio).");
        for (int i = 0; i < serverData.album.Count; i++)
        {
            Album item = serverData.album[i];
            for (int j = 0; j < item.radioList.Count; j++)
            {
                RadioInfo ritem = item.radioList[j];
                if (ritem.status == 0) continue;
                if (ritem.is_recommand == 1)
                {
                    RadioViewItem tmp = new RadioViewItem();
                    tmp.desStr = ritem.desc;
                    tmp.diversityNum = 0;
                    tmp.diversityTag = 0;
                    tmp.episodeTag = ritem.rid;
                    tmp.imgUrl = ritem.cover_url;
                    tmp.audioUrl = ritem.addr;
                    tmp.isDiversity = false;
                    tmp.itemState = ritem.free;
                    tmp.nameStr = ritem.name;
                    tmp.leadershipTag = -1;//-1 特指 编辑推荐

                    //特殊处理.
                    RadioViewItem it = new RadioViewItem();
                    it.imgUrl = tmp.imgUrl;
                    it.leadershipTag = item.cid;
                    it.episodeTag = tmp.episodeTag;

                    tmp.imgLocalPath = it.imgLocalPath;
                    list.Add(tmp);
                }

            }
        }
        list.Sort();
        
        return list;
    }

    //三个类型的默认设置[模板]
    protected RadioTagViewItem GetDefaultTab(RadioTagViewState state)
    {
        if (localConfig == null) throw new System.Exception("Default data null(Radio).");
        for (int i = 0; i < localConfig.viewItemList.Count; i++)
        {
            RadioTagViewItem item = localConfig.viewItemList[i];
            if (item.state == state)
            {
                return item;
            }
        }
        return null;
    }

    public List<RadioViewItem> GetPlayList(int id)
    {
        List<RadioViewItem> listSource = GetViewData(id);
        for (int i = listSource.Count-1; i >= 0; i--)
        {
            if (listSource[i].itemState == 0)
                listSource.RemoveAt(i);
        }
        return listSource;
    }

    public string GetJsonByTabID(int id)
    {
        List<RadioViewItem> listSource = GetViewData(id);
        List<RadioJsonData> list = new List<RadioJsonData>();
        
        for (int i = 0,j=0; i < listSource.Count; i++)
        {
            RadioViewItem item = listSource[i];
            if (item.itemState == 0) continue;//过滤掉未购买的.
            RadioJsonData tmp = new RadioJsonData();
            tmp.AudioID = j++;
            tmp.audioMainTitle = item.nameStr;
            tmp.audioSubTitle = item.desStr;
#if UNITY_EDITOR
            tmp.audioUrl = item.audioUrl;
            tmp.audioBgUrl = item.imgLocalPath;
#else
            tmp.audioUrl = item.audioUrl;
            tmp.audioBgUrl = item.imgLocalPath;
#endif
            list.Add(tmp);
        }
        JsonSerialization<RadioJsonData> jsonList = new JsonSerialization<RadioJsonData>(list);
        Debug.Log(list.Count);
        return JsonUtility.ToJson(jsonList);
    }
    /*
    protected Dictionary<int, RadioJsonInfo> radioTotalTime;
    public RadioJsonInfo GetRadioInfo(int audioID)
    {
        if (radioTotalTime == null) return null;
        if (radioTotalTime.ContainsKey(audioID))
            return radioTotalTime[audioID];
        else
            return null;
    }

    public void UpdateRadioInfo(string json)
    {
        if (radioTotalTime == null) radioTotalTime = new Dictionary<int, RadioJsonInfo>();
        RadioJsonInfo ji = JsonUtility.FromJson<RadioJsonInfo>(json);
        radioTotalTime[ji.audioID] = ji;
        Debug.Log(json);
    }

    public void ClearRadioInfo()
    {
        if (radioTotalTime != null) radioTotalTime.Clear();
    }*/
}